package org.xw.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xw.dto.AddPersonDto;
import org.xw.dto.FriendDto;
import org.xw.dto.UserDto;
import org.xw.pojo.UserPojo;
import org.xw.service.UserService;
import org.xw.utils.JWTUtil;
import org.xw.utils.ResponseUtil;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService service;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 传入电话号码phone以及密码password进行用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResponseUtil signUser(@RequestBody UserPojo user) {
        Boolean result = service.signUser(user);
        if (result) {
            return ResponseUtil.success("注册成功!");
        } else return ResponseUtil.error("注册失败!");
    }

    /**
     * 传入用户电话号码phone以及密码password登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public ResponseUtil login(@RequestBody UserPojo user) {
        System.out.println(user);
        HashMap<String, Object> login = service.login(user.getPhone(), user.getPassword());
        if (login!= null){
            if (login.isEmpty()) {
                return ResponseUtil.error("登录失败，请检查账号与密码后重新登录！");
            } else if (login.get("error") != null) {
                return ResponseUtil.error("密码错误");
            } else {
                return ResponseUtil.success(login);
            }
        }
        else return ResponseUtil.error("数据库没有数据");
    }

    /**
     * 通过请求头携带的token解析用户id，获取用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("")
    public ResponseUtil getUserInfo(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null) {
            HashMap selfInfo = service.getSelfInfo(request);

            if (selfInfo != null) {
                return ResponseUtil.success(selfInfo);
            } else return ResponseUtil.error("服务器错误!");
        } else return ResponseUtil.error("请先登录!");
    }


    /**
     * 解析token，查询该用户的好友列表
     *
     * @return
     */
    @GetMapping("/friendList")
    public ResponseUtil getFriendInfo(HttpServletRequest request) {
        String userIdStringForm = JWTUtil.analyzeToken(request, "Authorization", "user_id");
        List friendInfo = service.getFriendInfo(Integer.valueOf(userIdStringForm));
        if (friendInfo != null) {
            return ResponseUtil.success(friendInfo);
        } else return ResponseUtil.error("未查询到数据!");
    }

    /**
     * 查询单个好友的信息
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/friend")
    public ResponseUtil friendInfo(Integer id, HttpServletRequest request) {
        FriendDto friendDto = service.friendInfo(id, request);
        if (friendDto != null) {
            return ResponseUtil.success(friendDto);
        } else return ResponseUtil.error("未查询到数据");
    }

    /**
     * 传入目标好友的id，自身信息对象user，向目标好友发送好友请求
     *
     * @param addPerson
     * @return
     */
    @PostMapping("/addFriend")
    public ResponseUtil sendFriendRequest(@RequestBody AddPersonDto addPerson) {
        System.out.println(addPerson);
        Boolean result = service.sendFriendRequest(addPerson);
        if (result) {
            return ResponseUtil.success("发送请求成功!");
        } else return ResponseUtil.error("已发送申请!");
    }


    /**
     * 传入用户好友申请对象，携带授权authorization进行用户是否同意好友申请的修改
     *
     * @param friendRequest
     * @return
     */
    @PutMapping("/isAgree")
    public ResponseUtil agreeFriendRequest(@RequestBody FriendDto friendRequest) {
        Integer result = service.agreeRequest(friendRequest);
        UserDto userInfo = friendRequest.getUserInfo();
        String username = "用户";
        if (userInfo != null) {
            String name = userInfo.getUsername();
            if (name != null) {
                username = name;
            }
        }
        if (result == 1) {
            return ResponseUtil.success("你同意了" + username + "的好友申请!");
        } else if (result == 2) {
            return ResponseUtil.success("你拒绝了" + username + "的好友申请!");
        } else return ResponseUtil.error("操作失败!");
    }

    /**
     * 只传入用户id，查询数据库中所有好友请求
     *
     * @param
     * @return
     */
    @GetMapping("/friends")
    public ResponseUtil getFriendRequests(HttpServletRequest request) {
        String s = JWTUtil.analyzeToken(request, "Authorization", "user_id");
        if (s != null){
            List list = service.friendRequests(Integer.valueOf(s));
            if (list != null) {
                return ResponseUtil.success(list);
            } else return ResponseUtil.success("未收到好友申请");
        }else return ResponseUtil.error("你还没有登录");


    }


    /**
     * 传入想要删除的好友对象，将其authorization修改为3，并将数据中的userId以及friendId进行互换，修改对应数据的authorization为3
     *
     * @param targetFriend
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseUtil deleteFriend(@RequestBody FriendDto targetFriend) {
        String username = "";
        UserDto userInfo = targetFriend.getUserInfo();
        if (userInfo != null) {
            String name = userInfo.getUsername();
            if (name != null) {
                username = name;
            }
        }
        Boolean result = service.deleteFriend(targetFriend);
        if (result) {
            return ResponseUtil.success("成功删除好友" + username + "!");
        } else return ResponseUtil.error("删除失败!");
    }

    /**
     * 传入一段文本，将文本放入user表以及gzh表进行模糊搜索，将返回值返回给用户
     *
     * @param content
     * @return
     */
    @GetMapping("/search")
    public ResponseUtil searchInfo(String content, HttpServletRequest request) {
        HashMap hashMap = service.searchInfo(content, request);
        if (hashMap != null) {
            if (hashMap.isEmpty()) {
                return ResponseUtil.error("未查询到数据!");
            } else return ResponseUtil.success(hashMap);
        } else return ResponseUtil.error("请先登录");

    }


    /**
     * 用户传入新昵称，后台根据请求头携带的token解析用户id，并进行对应修改
     *
     * @param newName
     * @param request
     * @return
     */
    @PutMapping("/rename")
    public ResponseUtil updateName(String newName, HttpServletRequest request) {
        Integer integer = service.updateUsername(newName, request);
        if (integer == 1) {
            return ResponseUtil.success("修改成功!");
        } else if (integer == 2) {
            return ResponseUtil.error("修改失败!");
        } else return ResponseUtil.error("请先登录!");
    }


    /**
     * 传入用户文件，通过解析请求头token获取用户id，进行对应修改
     *
     * @param headImage
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public ResponseUtil updateHeadImage(MultipartFile headImage, HttpServletRequest request) {
        Integer integer = service.updateHeadImage(headImage, request);
        if (integer == 1) {
            return ResponseUtil.success("修改成功");
        } else if (integer == 2) {
            return ResponseUtil.error("更新失败");
        } else if (integer == 3) {
            return ResponseUtil.error("头像更新失败");
        } else return ResponseUtil.error("请先登录");

    }

    /**
     * 用户传入新地址address，解析token获取用户ID，进行地址更新
     *
     * @param userInfo
     * @param request
     * @return
     */
    @PostMapping("/newInfo")
    public ResponseUtil updateAddress(@RequestBody UserPojo userInfo, HttpServletRequest request) {
        Boolean result = service.updateAddress(request, userInfo);
        if (result) {
            return ResponseUtil.success("信息已更新");
        } else return ResponseUtil.error("更新失败，服务器错误");
    }

    /**
     * 传入好友数据主键id，好友用户id，备注内容，进行备注设置
     *
     * @param friend
     * @param request
     * @return
     */
    @PostMapping("/remark")
    public ResponseUtil setFriendRemark(@RequestBody FriendDto friend, HttpServletRequest request) {
        Boolean res = service.setFriendRemark(friend, request);
        if (res) {
            return ResponseUtil.success("已为好友设置备注");
        } else return ResponseUtil.error("设置失败");
    }

    /**
     * 提交解封请求   用户在被封禁后可提交解封请求，等待管理员解封
     *
     * @param request 请求，从中获取用户id
     * @return 是否成功的响应
     */
    @PostMapping("/unseal")
    public ResponseUtil addUnsealRequest(HttpServletRequest request) {
        Boolean result = service.addUnsealRequest(request);
        if (result) {
            return ResponseUtil.success(true);
        } else return ResponseUtil.error("提交请求失败，请检查提交信息是否完整");
    }

    /**
     * 登出    通过请求头携带的token解析id，将redis中所有对应数据删除实现登出
     *
     * @param request 请求
     * @return 是否成功的响应
     */
    @DeleteMapping("/logout")
    public ResponseUtil logout(HttpServletRequest request) {
        Boolean logout = service.logout(request);
        if (logout) {
            return ResponseUtil.success("登出成功");
        } else return ResponseUtil.error("登出失败");
    }


    /**
     * 传入手机号，获取验证码
     *
     * @param phone
     * @return
     */
    @GetMapping("/getNumber")
    public ResponseUtil getRandomNumber(String phone) {
        Boolean result = service.loginByPhone(phone);
        if (result) {
            return ResponseUtil.success("已发送验证码");
        } else return ResponseUtil.error("请求失败");
    }

    /**
     * 传入电话号码与获得的验证码，验证码一致则登录成功
     *
     * @param phone
     * @param code
     * @return
     */
    @GetMapping("/login")
    public ResponseUtil loginByPhone(String phone, Integer code) {
        HashMap hashMap = service.loginByPhone(phone, code);
        if (hashMap.get("error") != null) {
            return ResponseUtil.error((String) hashMap.get("error"));
        } else if (hashMap.get("error") == null && !hashMap.isEmpty()) {
            return ResponseUtil.success(hashMap);
        } else
            return ResponseUtil.error("服务器错误");
    }
}
